package cn.shenshen.shop.web.controller;

import cn.shenshen.shop.domain.OrderInfo;
import cn.shenshen.shop.domain.SeckillOrder;
import cn.shenshen.shop.domain.User;
import cn.shenshen.shop.service.IOrderInfoService;
import cn.shenshen.shop.service.ISeckillGoodService;
import cn.shenshen.shop.service.ISeckillOrderService;
import cn.shenshen.shop.util.Result;
import cn.shenshen.shop.util.SeckillServerCodeMsg;
import cn.shenshen.shop.vo.GoodVo;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 秒杀控制器
 */
@RestController
@RequestMapping("api/seckillOrder")
public class SeckillOrderController {

    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderInfoService orderInfoService;

    @RequestMapping("/doSeckill")
    public Result<String> doSeckill(Long goodId, User user){

        //用户必须登录
        if (user == null){
            return Result.error(SeckillServerCodeMsg.LOGIN_ERROR);
        }
        //必须要有对应的秒杀商品
        GoodVo goodVo = seckillGoodService.find(goodId);
        if (goodVo == null){
            return Result.error(SeckillServerCodeMsg.OP_ERROR);
        }
        //判断秒杀是否已经开始
        if ((goodVo.getStartDate().getTime()-new Date().getTime()) > 0){
            return Result.error(SeckillServerCodeMsg.OP_ERROR);
        }
        //判断库存
        if (goodVo.getStockCount()<= 0){
            return Result.error(SeckillServerCodeMsg.STOCK_OVER);
        }
        //判断是否重复下单
        SeckillOrder seckillOrder = seckillOrderService.find(user.getId(),goodId);
        if (seckillOrder!=null){
            return Result.error(SeckillServerCodeMsg.SECKILL_REPEAT);
        }

        //检验完成进行秒杀操作
        String orderInfo = orderInfoService.doSeckill(user.getId(),goodId);
        return Result.success(orderInfo);
    }

    @RequestMapping("/find")
    public Result<OrderInfo> find(String orderNo, User user){
        if (user == null){
            return Result.error(SeckillServerCodeMsg.LOGIN_ERROR);
        }
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        return Result.success(orderInfo);
    }
}

